#!/usr/bin/env Rscript

setwd("/home/projects/ku_00156/scratch/ssato/MICROGNATHOZOA/transcriptome/delimitr")

observedSFS <- 'Limno_MSFS'
traitsfile <- 'Limno_traits.txt'
observedtree <- '((0,1),2);'
migmatrix <- matrix(c(FALSE, TRUE, FALSE,
                    TRUE, FALSE, FALSE,
                    FALSE, FALSE, FALSE),
                    nrow = 3, ncol = 3, byrow = TRUE)
divwgeneflow <- TRUE
seccontact <- TRUE
maxedges <- 1
obsspecies<- 3
obssamplesize <- c(6,4,4)
obssnps <- 5083
obsprefix <- 'Limno_guidetree1'
obspopsizeprior <- list(c(1000,100000),c(1000,100000),c(1000,100000))
obsdivtimeprior <- list(c(1000,1000000),c(10000,1000000))
myrules <- c('Tdiv2$>Tdiv1$')
obsmigrateprior <- list(c(0.000005,0.00005))

library(delimitR)

setup_fsc2(tree=observedtree,
           nspec=obsspecies,
           samplesizes=obssamplesize,
           nsnps=obssnps,
           prefix=obsprefix,
           migmatrix=migmatrix,
           popsizeprior=obspopsizeprior,
           divtimeprior=obsdivtimeprior,
           migrateprior=obsmigrateprior,
           secondarycontact= seccontact,
           divwgeneflow= divwgeneflow,
           maxmigrations = maxedges,
           myrules = myrules)

fastsimcoalsims(prefix=obsprefix,
                pathtofsc='/services/tools/fastsimcoal/2.6.0.3/fsc26',
                nreps=10000)

nclasses <- 4

FullPrior <- makeprior(prefix=obsprefix,
                       nspec=obsspecies,
                       nclasses=nclasses,
                       getwd(),
                       traitsfile = traitsfile,
                       threshold=100, 
                       thefolder = 'Prior',
                       ncores = 10)
                       
clean_working(prefix=obsprefix)

ReducedPrior <- Prior_reduced(FullPrior)

myRF <- RF_build_abcrf(ReducedPrior,FullPrior,5000)

myRF

myobserved <- prepobserved(
  observedSFS,
  FullPrior,
  ReducedPrior,
  nclasses,
  obsspecies,
  traitsfile=traitsfile,
  threshold = 100)

prediction <- RF_predict_abcrf(myRF, myobserved, ReducedPrior, FullPrior, 5000)

prediction